﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace AsscerMVCN2512.Controllers
{
    public class SchoolController : Controller
    {
        AssetDBEntities1 db = new AssetDBEntities1();

        // GET: School
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetCampusData(int page, int limit, string strCampusName = null)
        {
            try
            {
                int offset = limit * (page - 1);

                string sql = "SELECT CampusID, CampusName, CampusReMark FROM CampusInfo WHERE 1=1";
                var parameters = new List<System.Data.SqlClient.SqlParameter>();

                if (!string.IsNullOrEmpty(strCampusName))
                {
                    sql += " AND CampusName LIKE @CampusName";
                    parameters.Add(new System.Data.SqlClient.SqlParameter("@CampusName", "%" + strCampusName + "%"));
                }

                List<CampusInfoViewModel> list = db.Database.SqlQuery<CampusInfoViewModel>(sql, parameters.ToArray()).ToList();
                var data = list.OrderBy(x => x.CampusID).Skip(offset).Take(limit);

                db.Configuration.LazyLoadingEnabled = false;
                var json = new
                {
                    code = 0,
                    msg = "",
                    count = list.Count,
                    data = data
                };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<CampusInfoViewModel>()
                }, JsonRequestBehavior.AllowGet);
            }
        }

        // 检查校区名称是否已存在
        public ActionResult IsCampusNameExists(string campusName, string excludeId)
        {
            if (string.IsNullOrEmpty(campusName))
            {
                return Json(new { code = 0 }, JsonRequestBehavior.AllowGet);
            }

            var exists = db.CampusInfo.Any(c => c.CampusName == campusName);

            if (!string.IsNullOrEmpty(excludeId) && int.TryParse(excludeId, out int id))
            {
                exists = db.CampusInfo.Any(c => c.CampusName == campusName && c.CampusID != id);
            }

            return Json(new { code = exists ? 1 : 0 }, JsonRequestBehavior.AllowGet);
        }

        // 添加校区
        [HttpPost]
        public ActionResult AddCampus(CampusInfoViewModel model)
        {
            ModelState.Remove("CampusID");

            if (ModelState.IsValid)
            {
                try
                {
                    if (db.CampusInfo.Any(c => c.CampusName == model.CampusName))
                    {
                        return Json(new { code = 1, msg = "校区名称已存在！" });
                    }

                    var newCampus = new CampusInfo
                    {
                        CampusName = model.CampusName,
                        CampusReMark = model.CampusReMark
                    };

                    db.CampusInfo.Add(newCampus);
                    db.SaveChanges();
                    return Json(new { code = 0, msg = "添加成功！" });
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "添加失败：" + ex.Message });
                }
            }
            var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
            return Json(new { code = 1, msg = "数据验证失败！" + string.Join(" ", errors) });
        }

        // 更新校区
        [HttpPost]
        public ActionResult UpdateCampus(CampusInfoViewModel model)
        {
            if (ModelState.IsValid && model.CampusID > 0)
            {
                try
                {
                    if (db.CampusInfo.Any(c => c.CampusName == model.CampusName && c.CampusID != model.CampusID))
                    {
                        return Json(new { code = 1, msg = "校区名称已存在！" });
                    }

                    var campusToUpdate = db.CampusInfo.Find(model.CampusID);
                    if (campusToUpdate == null)
                    {
                        return Json(new { code = 1, msg = "未找到该校区！" });
                    }

                    campusToUpdate.CampusName = model.CampusName;
                    campusToUpdate.CampusReMark = model.CampusReMark;

                    db.Entry(campusToUpdate).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { code = 0, msg = "更新成功！" });
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "更新失败：" + ex.Message });
                }
            }
            return Json(new { code = 1, msg = "数据验证失败！" });
        }

        // 删除校区
        [HttpPost]
        public ActionResult DeleteCampus(int campusId)
        {
            try
            {
                var campusToDelete = db.CampusInfo.Find(campusId);
                if (campusToDelete == null)
                {
                    return Json(new { code = 1, msg = "删除失败：未找到该校区。" });
                }
                db.CampusInfo.Remove(campusToDelete);
                db.SaveChanges();
                return Json(new { code = 0, msg = "删除成功！" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }
    }
}